/*
 * @Date: 2024-06-21 14:37:24
 */
const loaded = require('./loaded.js');
new loaded().Loop((env, num) => {
    console.clear();
    var HomeData = fun.getHomeData();
    //签到
    var signData = fun.sign(HomeData);
    if (signData) {
        log.success("[" + HomeData.pastureInfoData.userName + "]: 签到成功");
    }

    //采摘
    var ports = [];
    for (let port_iv = 0; port_iv < HomeData.portList.length; port_iv++) {
        var port = HomeData.portList[port_iv];
        if (port.state != 8) continue;
        ports.push(port);
    }
    if (ports.length > 0) {
        var res = fun.harvestAllCrop();
        if (res) {
            var names = [];
            for (var i = 0; i < ports.length; i++) {
                names.push(ports[i].goodsName);
            }
            log.success("[" + HomeData.pastureInfoData.userName + "]: 一键采摘成功(" + names.join(", +") + ")");
        }
    }


    //铲地
    for (let port_iv = 0; port_iv < HomeData.portList.length; port_iv++) {
        var port = HomeData.portList[port_iv];
        if (port.state != 0) continue;
        var res = fun.portOperationAll("2");
        if (!res) break;
        log.success("[" + HomeData.pastureInfoData.userName + "]: 一键铲地成功");
        HomeData = fun.getHomeData();
    }

    //种地
    for (let port_iv = 0; port_iv < HomeData.portList.length; port_iv++) {
        var port = HomeData.portList[port_iv];
        if (port.state != 1) continue;
        var goodsData = fun.getMyKnapsackList();
        if (!goodsData) {
            if (fetch()) {
                goodsData = fun.getMyKnapsackList();
            } else {
                break;
            }
        }
        var res = fun.sow(port, goodsData);
        if (!res) continue;
        log.success("[" + HomeData.pastureInfoData.userName + "]:" + goodsData.name + ":种地成功");
        HomeData = fun.getHomeData();
    }

    //一键操作
    for (let port_iv = 0; port_iv < HomeData.portList.length; port_iv++) {
        var port = HomeData.portList[port_iv];
        if (!port.isWater && !port.isWeed && !port.isInsects) continue;
        var res = fun.portOperationAll("1");
        if (!res) break;
        log.success("[" + HomeData.pastureInfoData.userName + "]: 一键操作成功");
        HomeData = fun.getHomeData();
        break;
    }

    //尝试卖出多余的植物
    var res = fun.getMyWarehouseList();
    if (res) {
        for (let i = 0; i < res.length; i++) {
            var saleExp = res[i].saleExp * res[i].warehouseNum;
            var estimatedRevenue = res[i].estimatedRevenue * res[i].warehouseNum;
            fun.sellGoods(res[i]);
            log.success("[" + HomeData.pastureInfoData.userName + "]: 卖出植物" + res[i].goodsName + "成功(收益:" + estimatedRevenue + ", 经验:" + saleExp + ")");
        }
        HomeData = fun.getHomeData();
    }

    //找一个进行施肥
    for (let port_iv = 0; port_iv < HomeData.portList.length; port_iv++) {
        let port = HomeData.portList[port_iv];
        if (!port.nextTime) continue;
        if (!(port.nextTime.match(/[0-9]+时/))) continue;
        let portTime = port.nextTime.match(/[0-9]+时/)[0].match(/[0-9]+/)[0];
        let FertilizerList = fun.getMyFertilizerList();
        let test_num = parseInt(HomeData.pastureInfoData.money / 1000);//理论最多肥料数量
        var now_num = 0;
        for (let i = 0; i < FertilizerList.length; i++) {
            const Fertilizer = FertilizerList[i];
            if (Fertilizer.total_time != 60) continue;
            now_num = Fertilizer.num;
            FertilizerList[i].num += test_num;
        }
        if (!now_num) {//没有低级肥料
            if (!env.buyFertilizer) break;
            if (HomeData.pastureInfoData.money >= 1000) {
                if (fun.buyFertilizer() === false) {
                    log.warning("[" + HomeData.pastureInfoData.userName + "]: 购买肥料失败");
                } else {
                    log.success("[" + HomeData.pastureInfoData.userName + "]: 购买肥料成功");
                }
                HomeData = fun.getHomeData();
                FertilizerList = fun.getMyFertilizerList();
                test_num = parseInt(HomeData.pastureInfoData.money / 1000);
                for (let i = 0; i < FertilizerList.length; i++) {
                    if (FertilizerList[i].total_time != 60) continue;
                    FertilizerList[i].num += test_num;
                    now_num = 1;
                }
            } else {
                log.warning("[" + HomeData.pastureInfoData.userName + "]: 金币不足, 购买肥料失败");
            }
        }
        FertilizerList = getFertilizerPlan(portTime, FertilizerList);
        for (let Fertilizer_iv = 0; Fertilizer_iv < FertilizerList.length; Fertilizer_iv++) {
            let Fertilizer = FertilizerList[Fertilizer_iv];
            if (!env.buyFertilizer) break;
            if (Fertilizer.total_time == 60 && Fertilizer.num > now_num) {//需要购买
                if (fun.buyFertilizer(Fertilizer.num - now_num) === false) {
                    log.warning("[" + HomeData.pastureInfoData.userName + "]: 购买肥料失败");
                } else {
                    log.success("[" + HomeData.pastureInfoData.userName + "]: 购买" + (Fertilizer.num - now_num) + "个肥料成功");
                }
            }
            if (fun.fertilize(port, Fertilizer, Fertilizer.num)) {
                log.success("[" + HomeData.pastureInfoData.userName + "]:" + port.goodsName + "使用" + Fertilizer.num + "个" + Fertilizer.name + "施肥成功");
                HomeData = fun.getHomeData();
                break;
            }
        }
        function getFertilizerPlan(total_time, Fertilizers) {
            Fertilizers.sort((a, b) => b.total_time - a.total_time);
            let remainingTime = total_time * 60;
            let usedFertilizers = [];

            for (let fertilizer of Fertilizers) {
                let usedCount = Math.min(Math.floor(remainingTime / fertilizer.total_time), fertilizer.num);
                remainingTime -= usedCount * fertilizer.total_time;
                if (usedCount > 0) {
                    fertilizer.num = usedCount;
                    usedFertilizers.push(fertilizer);
                }
            }
            return usedFertilizers;
        }
    }

    // 获取种子
    function fetch() {
        function treasure(Treasure) {
            let props = fun.getTreasureDetail(Treasure);
            if (!props) {
                // 没有道具, 去试着合成
                for (let i = 1; i < 2; i++) {
                    if (!fun.getMakeMsg(i)) continue;
                    if (!fun.make(i)) return false;
                }
            }
            props = fun.getTreasureDetail(Treasure);
            if (!props) log.info("[" + HomeData.pastureInfoData.userName + "]: 藏宝图不足, 合成失败");
            let prop = props.data[Math.floor(Math.random() * props.data.length)];
            return prop;
        }
        let Treasure = fun.getTreasureList();
        if (!Treasure) return false;
        do {
            let res = treasure(Treasure);
            if (!res) {
                //购买藏宝图
                if (HomeData.pastureInfoData.money >= 1500) {
                    if (HomeData.pastureInfoData.money >= 5000) {//购买高级藏宝图
                        if (fun.shopadd(176)) log.info("[" + HomeData.pastureInfoData.userName + "]: 种子不足, 购买高级藏宝图")
                    } else {//购买普通藏宝图
                        if (fun.shopadd(175)) log.info("[" + HomeData.pastureInfoData.userName + "]: 种子不足, 购买普通藏宝图")
                    }
                } else {
                    log.warning("[" + HomeData.pastureInfoData.userName + "]: 金币不足, 无法购买藏宝图")
                    return false;
                }
            }
            if (fun.openTreasure(res.id)) log.info("[" + HomeData.pastureInfoData.userName + "]: 使用藏宝图成功")
        } while (!fun.getMyKnapsackList());
        let KnapsackList = fun.getMyKnapsackList();
        let tests = [];
        for (let i = 0; i < KnapsackList.length; i++) {
            tests.push(KnapsackList[i].name + "x" + KnapsackList[i].num);
        }
        log.info("[" + HomeData.pastureInfoData.userName + "]: 成功通过藏宝图获取种子(" + tests.join(", ") + ")")
        return true;
    }

    //获取动物来访
    for (let i = 0; i < HomeData.animalList.length; i++) {
        let animal = HomeData.animalList[i];
        log.success("[" + HomeData.pastureInfoData.userName + "]: " + animal.animalName + "来访");
        let ybqs = fun.getybqList();
        let catchs = false;
        for (let ybq_iv = 0; ybq_iv < ybqs.length; ybq_iv++) {
            const ybq = ybqs[ybq_iv];
            if (catchs) break;
            for (let use_num = 0; use_num < ybq.num; use_num++) {
                if (!fun.catch(ybq, animal)) {
                    catchs = true;
                    break;
                }
            }
        }
        if (!catchs) log.warning("[" + HomeData.pastureInfoData.userName + "]: 诱捕球耗尽,没有抓到动物");
        while (!catchs) {
            if (HomeData.pastureInfoData.money >= 1000) {
                fun.buyybq();
                let ybqs = fun.getybqList();
                if (!fun.catch(ybqs[0], animal)) {
                    catchs = true;
                }
            } else {
                log.warning("[" + HomeData.pastureInfoData.userName + "]: 购买诱捕球失败")
                break;
            }
        }
    }

    //判断是否符合动物标准,如果符合则获取数据
    var FarmData = false;
    if (HomeData.pastureInfoData.pasture_level >= 10) FarmData = fun.getFarmData();
    //执行动物操作
    if (FarmData) {
        //整体判断是否需要饲料
        if ((env.usedelicate && (FarmData.feeds.delicate_num_total > FarmData.feeds.delicate_num)) || FarmData.feeds.ordinary_num_total > FarmData.feeds.ordinary_num) {
            let feeds = fun.getFeedList();
            let ordinary_num = 0;//普通饲料数量
            let delicate_num = 0;//精致饲料数量
            let ordinary_feed = {goods_id:2337};
            let delicate_feed = {goods_id:3698};
            for (let feeds_iv = 0; feeds_iv < feeds.length; feeds_iv++) {
                if (feeds[feeds_iv].id == 6507857) {
                    ordinary_num = feeds[feeds_iv].num;
                    ordinary_feed = feeds[feeds_iv];
                }
                if (feeds[feeds_iv].id == 6489580) {
                    delicate_num = feeds[feeds_iv].num;
                    delicate_feed = feeds[feeds_iv];
                }
            }
            //判断是否需要添加普通饲料
            if (FarmData.feeds.ordinary_num_total > FarmData.feeds.ordinary_num) {
                let need_num = FarmData.feeds.ordinary_num_total - FarmData.feeds.ordinary_num;
                if (ordinary_num >= need_num) {//直接使用饲料
                    fun.useFeed(ordinary_feed);
                } else {//购买饲料
                    if (fun.buyFeed(ordinary_feed.goods_id,need_num - ordinary_num) === false) {
                        log.warning("[" + HomeData.pastureInfoData.userName + "]: 购买普通饲料失败")
                    } else {
                        fun.useFeed(ordinary_feed);
                    }
                }
            }

            //判断是否需要添加精致饲料
            if (env.usedelicate && (FarmData.feeds.delicate_num_total > FarmData.feeds.delicate_num)) {
                let need_num = FarmData.feeds.delicate_num_total - FarmData.feeds.delicate_num;
                if (delicate_num >= need_num) {//直接使用饲料
                    fun.useFeed(delicate_feed);
                } else {//购买饲料
                    if (fun.buyFeed(delicate_feed.goods_id,  need_num - delicate_num) === false) {
                        log.warning("[" + HomeData.pastureInfoData.userName + "]: 购买精致饲料失败")
                    } else {
                        fun.useFeed(delicate_feed);
                    }
                }
            }
            FarmData = fun.getFarmData();
        }

        //判断是否需要收获
        for (let i = 0; i < FarmData.portList.length; i++) {
            const animal = FarmData.portList[i];
            if (animal.state != 8) continue;
            if (fun.harvestAllAnimal()) {
                log.log("[" + HomeData.pastureInfoData.userName + "]: 一键收获成功");
                FarmData = fun.getFarmData();
                break;
            }
        }

        //判断是否需要操作
        for (let i = 0; i < FarmData.portList.length; i++) {
            const animal = FarmData.portList[i];
            if (animal.isWater || animal.isWeed || animal.isInsects) {
                //需要操作
                if (fun.farmOperationAll()) {
                    log.log("[" + HomeData.pastureInfoData.userName + "]: 一键操作成功");
                    FarmData = fun.getFarmData();
                    break;
                }
            }
        }

        //判断是否空闲,需要饲养动物
        for (let i = 0; i < FarmData.portList.length; i++) {
            const animal = FarmData.portList[i];
            if (animal.state != 0) continue;
            let animals = fun.getAnimal();
            if (!animals) {
                if (fetch_animals()) {
                    animals = fun.getAnimal();
                } else {
                    break;
                }
            }
            fun.useAnimal(animals, animal);
        }
        // console.log(FarmData)
    }

    function fetch_animals() {
        let shops = fun.getAnimalShopList();
        let shopAnimals = [];
        for (let i = 0; i < shops.length; i++) {
            const animal = shops[i];
            if (animal.price > HomeData.pastureInfoData.money) continue;
            shopAnimals.push(animal);
        }
        if (!shopAnimals.length) return false;
        let shop_data = shopAnimals[Math.floor(Math.random() * shopAnimals.length)];
        if (fun.buyAnimal(shop_data.id)) {
            log.log("[" + HomeData.pastureInfoData.userName + "]: 购买动物成功(" + shop_data.name + ")");
            return true;
        } else {
            log.log("[" + HomeData.pastureInfoData.userName + "]: 购买动物失败")
            return false;
        }
    }

    if (isAfter(23, 50)) {
        fun.receiveAllActiveReward(1);
        fun.receiveAllActiveReward(2);
        var items = [];
        for (let i = 1; i < 5; i++) {
            items = items.concat(fun.getSpecimenList(i))
        }
        for (let i = 0; i < items.length; i++) {
            const item = items[i];
            fun.makeSpecimen(item.id);
        }
        let animals = fun.getMyAnimal();
        if (animals) {
            for (let i = 0; i < animals.length; i++) {
                const animal = animals[i];
                fun.makeAnimal(animal.id,animal.goodsNum);
            }
        }
    }
    function isAfter(h, m) {
        const now = new Date();
        const hour = now.getHours();
        const minute = now.getMinutes();

        if (hour > h || (hour == h && minute >= m)) {
            return true;
        } else {
            return false;
        }
    }

})